package com.zlsy.thread.threadlocal;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zhouliang
 * @date 2020/07/11
 **/
public class ThreadLocalNormalUsage03 {

    //因为SimpleDateFormat不是线程安全的，所以我们看到有很多线程打印出来的时间是一样的。
    static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    public String date(int seconds) {
        Date date = new Date(1000 * seconds);
        return simpleDateFormat.format(date);
    }

    public static void main(String[] args) throws InterruptedException {
        //局部线程池，使用完要记得关闭
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                10,
                10,
                0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(),
                new BasicThreadFactory.Builder()
                        .namingPattern("thread-local-learning-%s")
                        .build());

        for (int i = 0; i < 1000; i++) {
            int finalI = i;
            threadPoolExecutor.execute(() -> {
                ThreadLocalNormalUsage03 usage02 = new ThreadLocalNormalUsage03();
                String date = usage02.date(finalI);
                System.out.println(Thread.currentThread().getName() + " 打印出:" + date);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        threadPoolExecutor.shutdown();
    }
}
